<?php
namespace App\Models\Product;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use Illuminate\Database\Eloquent\Model;

class ProductVariant extends Model{

    protected $table = 'product_variant';

    protected $guarded = [];

    protected $casts = [
        'parent_account' => 'array',
        'aplus_account' => 'array',
    ];

    public static $_parentStandard = [
        1 => '是',
        2 => '否'
    ];

    public function country(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(SysCountry::class,'country_id');
    }

    public function classify(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(ProductClassify::class,'classify_id');
    }

    public function plat(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(SysPlat::class, 'plat_id', 'plat_id');
    }

    /**
     * 获取格式化的账号
     * @param $accountIds
     * @return string
     */
    public static function formatAccount($accountIds): string
    {
        $res = AmazonAccount::query()->whereIn('id',$accountIds)->pluck('account')->toArray();
        return implode('，',$res);
//        return implode('；',collect($apply)->map(function ($item, $key){
//            return $key.':'.$item;
//        })->toArray());
    }

    public static function getAccountIdArrByAccountStr($accountStr): array
    {
        $accountArr = explode(',',str_replace('，',',',$accountStr));
        return AmazonAccount::query()->whereIn('account',$accountArr)->pluck('id')->toArray();
    }

    public static function getDownloadData($res): \Generator
    {
        foreach ($res as $model){
            $season = $model->classify->season ?? 3;
            $temp = [
                $model->plat->title ?? '',
                $model->country->country ?? '',
                $model->classify->title ?? '',
                array_key_exists($season,ProductClassify::$_season) ? ProductClassify::$_season[$season] : '',
                self::$_parentStandard[$model->parent_standard],
                self::formatAccount($model->parent_account),
                self::formatAccount($model->aplus_account),
            ];
            yield $temp;
        }
    }
}
